#include <stdio.h>
#include "mpi.h"
#include <stdlib.h>

const int num_steps = 2E9;

int main(int ac, char **av){
	int num_process, myid;
	double *buf, sum, step;
	double res, start, end;
	MPI_Init(&ac, &av);
	MPI_Comm_rank(MPI_COMM_WORLD, &myid);
	MPI_Comm_size(MPI_COMM_WORLD, &num_process);
	start = MPI_Wtime();
	if(myid == 0){
		buf = (double *)malloc(num_process * sizeof(double));
		step = 1.0L / num_steps;

	}
	MPI_Bcast(&step, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
	for(int i = myid + 1;i <= num_steps; i+= num_process){
		double x = (i - 0.5) * step;
		sum += 4.0L / (1.0L + x * x);
	} 
	MPI_Gather(&sum, 1, MPI_DOUBLE, buf, 1 , MPI_DOUBLE, 0, MPI_COMM_WORLD);
	// MPI_Gather(&sum, 1, MPI_DOUBLE, buf, num_process + 1 , MPI_DOUBLE, 0, MPI_COMM_WORLD);
	if(myid == 0){
		for(int i = 1; i < num_process; i++){
			sum += buf[i];
		}
		end = MPI_Wtime();
		printf("Size = %d, rank = %d, time = %f \n", num_process, myid,  (end - start));
		printf("pi = %.20lf\n", sum * step);
	}

	MPI_Finalize();

}


